package com.ibeetl.admin.core.web;

import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.FileUtil;
import com.ibeetl.admin.core.util.ImageCut;
import com.ibeetl.admin.core.util.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

@Controller
public class JcropContorller {
	private final Log log = LogFactory.getLog(this.getClass());

	@Autowired
	Environment env;
	@Autowired
	CorePlatformService platformService;

	private static final String MODEL = "/core/jcrop";

	@Autowired
	FileService fileService;

	@ResponseBody
	@RequestMapping("/jcropOperateImage")
	public JsonResult jcropOperateImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String fileId = request.getParameter("fileId");
		FileItem fileItem = this.fileService.getFileItemById(NumberUtils.toLong(fileId));
		if (fileItem == null) {
			return JsonResult.fail("文件不存在");
		}
		String root = FileItem.getRoot(env);
		String src = fileItem.getPath();
		String strX = request.getParameter("x");
		String strY = request.getParameter("y");
		String strWidth = request.getParameter("width");
		String strHeight = request.getParameter("height");
		String strBili = request.getParameter("bili");
		if (StringUtils.isBlank(strBili)) {
			strBili = "1";
		}
		strBili = "1";
		Double bili = Double.valueOf(strBili);
		// src = "/tatic/1/source/images/1.jpg";
		// strX = "1";
		// strY = "1";
		// strWidth = "3";
		// strHeight = "3";
		System.out.println(strX + strY + strHeight + strWidth);
		if (!(StringUtils.isBlank(src) || StringUtils.isBlank(strX) || StringUtils.isBlank(strY) || StringUtils.isBlank(strWidth) || StringUtils.isBlank(strHeight))) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String ymd = sdf.format(new Date());

			File srcFile = new File(root + File.separator + fileItem.getPath());
			File rotateFile = new File(root + File.separator + "rotate" + File.separator + fileItem.getPath());//旋转后的文件
			String path = File.separator + "jcrop" + File.separator + fileItem.getPath();
			File jcropFile = new File(root + path);//裁剪后的文件

			if (srcFile.exists()) {// 源文件存在
				File cutFile = srcFile;
				// 判断是否旋转
				Metadata metadata = null;
				try {
					metadata = JpegMetadataReader.readMetadata(srcFile);
					Directory exif = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);

					if (exif != null && exif.getTagCount() > 0) {
						String orientation = exif.getString(ExifIFD0Directory.TAG_ORIENTATION);
						Iterator iterator = exif.getTags().iterator();
						while (iterator.hasNext()) {
							Tag tag = (Tag) iterator.next();
							// System.out.println(tag);
						}

						// 如果旋转，调整
						BufferedImage old_img = (BufferedImage) ImageIO.read(srcFile);
						int w = old_img.getWidth();
						int h = old_img.getHeight();

						BufferedImage rotateBufferedImage = null;
						if (StringUtils.equals(orientation, "3")) {
							rotateBufferedImage = ImageCut.Rotate(ImageIO.read(srcFile), 180);
						} else {
							System.out.println("旋转类型：" + orientation);
						}
						if (rotateBufferedImage != null) {
							ImageIO.write(rotateBufferedImage, null, rotateFile);
							cutFile = new File(rotateFile.getPath());
						}
					}
				} catch (JpegProcessingException e) {
					// TODO Auto-generated catch block
					// e.printStackTrace();
				}
				//TODO
				ImageCut.imgCut(cutFile.getPath(), jcropFile.getPath(), bili, strX, strY, strWidth, strHeight);

				//System.out.println("源文件：" + srcFile.getPath() + ",生成文件：:" + jcropFile.getPath());

				//FileItem jcropFileItem = fileService.createFileItem(jcropFile.getName(), jcropFile.getName(), null, null, null, null, null, UUIDUtil.uuid(), null);
				FileItem jcropFileItem1 = fileService.createFileItem(jcropFile.getName(), jcropFile.getName(), path,null);

				//FileUtil.copy(FileUtils.openInputStream(jcropFile), jcropFileItem.openOutpuStream());
				return JsonResult.success(jcropFileItem1);
			} else {
				// 源文件不存在
				return JsonResult.fail("源文件不存在");
			}
		} else {
			return JsonResult.fail("参数不完整");
		}
	}
	
	 /*上传*/
   @PostMapping(MODEL + "/upload.json")
   @ResponseBody
   public JsonResult layuiUpload(@RequestParam("file") MultipartFile file,String batchFileUUID,String bizType,String bizId, String title, String url) throws IOException {
       if(file.isEmpty()) {
           return JsonResult.fail();
       }
       FileItem fileItem = fileService.createFileItem(file.getOriginalFilename(), null, null, "jcrop-upload", null, null, null, UUIDUtil.uuid(),null);
       OutputStream os = fileItem.openOutpuStream();
       FileUtil.copy(file.getInputStream(), os);
       
       //页面中需要显示文件路径，在这里组装成可以用的路径
       fileItem.setPath("/core/file/inline/" + fileItem.getId() + "/" + fileItem.getName());
       return JsonResult.success(fileItem);
   }
}
